package com.yiba.vpn.util;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

/**
 * 获取IP
 *
 * @author liuyang
 * 2017年6月19日
 */
public class Iputil {

    /**
     * 获取Ip
     *
     * @param request
     * @return
     */
    public static String getRequestIp(HttpServletRequest request) {

      /*  Enumeration<String> stringEnumeration = request.getHeaderNames();
        String key =null;
        do {
            try{
                key = stringEnumeration.nextElement();
                System.out.println("key=" + key + ";value=" + request.getHeader(key));
            }catch (Exception e){
                System.out.println(e.getMessage());
            }

        } while (key != null);
        System.out.println("Over");*/

        String ip = request.getHeader("x-forwarded-for");

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (StringUtils.isNotBlank(ip)) {
            ip = ip.split(",")[0];
        }
        return ip;
    }
}
